package com.p7.framework.permission.shiro.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 权限过滤器
 * @ClassName: ClientPermissionsCheckFilter 
 * @author p7+
 * @date 2019年2月25日 下午9:43:06 
 * @Copyright:
 */
public class ClientPermissionsCheckFilter extends AccessControlFilter {

	private static final Logger LOGGER = LoggerFactory.getLogger(ClientPermissionsCheckFilter.class);

	@Override
	public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {

		Subject subject = getSubject(request, response);
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		// 发布的项目名 + 接口路径
		LOGGER.info("requestURI : {} ", httpRequest.getRequestURI());
		// 全路径
		LOGGER.info("requestURL : {} ", httpRequest.getRequestURL());
		// 发布的项目名
		LOGGER.info("contextPath : {} ", WebUtils.getContextPath(httpRequest));
		// 
		LOGGER.info("contextPath : {} ", WebUtils.getPathWithinApplication(httpRequest));
		
		if (subject.isPermitted(WebUtils.getPathWithinApplication(httpRequest))) {
			return true;
		}

		return false;
	}

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");

        PrintWriter out = httpServletResponse.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        out.write(mapper.writeValueAsString("当前用户没有访问权限"));
        out.flush();
        out.close();

        return false;
    }
}
